<template>
  <div>
    <div>
      <FormPanel
        ref="formPanel"
        :list="formList"
        :cols="2"
        :formType="type"
        labelWidth="110"
        :isSubmitBtn="false"
        @formChange="formChangeHandle"
      />
    </div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog">取消</el-button>
      <el-button @click="saveDialog" type="primary">确定</el-button>
    </div>
  </div>
</template>

<script>
import {
  getCompanyOrgIsMerge,
  getOrgType,
  getDealerArea
} from '@/api/potenCus/customer/potenCusManage';
import {
  updateDealers
} from '@/api/potenCus/customer/potenCusManageOEM'
import {
  addTestDriveCars,
  editTestDriveCars
 } from '@/api/potenCus/basedata/searchTestDriveCars';
import { dictionary } from '@/utils/dictMixin';
import { VIN, phone } from '@/utils/validate'

export default {
  name: 'searchDealers',
  mixins: [dictionary],
  props: {
    type: {
      type: String,
      default: 'add'
    },
    rowData: {
      type: Object,
      default: () => ({})
    },
    selectList: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    this.saveData = null;
    return {
      formList: this.createFormList(),
      allOrgId: []
    };
  },
  created() {
    this.init();
  },
  methods: {
    async init() {
      // 事业部
        // 当前经销商有无小区 是否合并
        const res = await getCompanyOrgIsMerge()
        console.log('是否合并',res)
        // isDisArea： 10041001 只有大区   10041002 ：有小区
        // isMerge ：10041001 销售售后合并  10041002 ：不合并
        let {isDisArea, isMerge} = res.data
        // 1. 不合并只大区 传15061005
        if(isDisArea == 10041001 && isMerge == 10041002 ){
          // 查询经销商代码
          const res1 = await getOrgType(15061005);
          this.allOrgId = res1.data.map(x=> ({ value: JSON.stringify(x), text: x.orgName }))
          console.log('经销商代码1',this.allOrgId)
          if(res1.resultCode == 200){
            this.formList.find(item => item.fieldName ==='orgId').itemList = this.allOrgId
          }
        }
        // 2. 不合并大小区 传15061005 ,15061007
        if(isDisArea == 10041002 && isMerge == 10041002 ){
          const res2 = await getOrgType(15061005,15061007);
          this.allOrgId = res2.data.map(x=> ({ value: JSON.stringify(x), text: x.orgName }))
          console.log('经销商代码2', this.allOrgId)
          if(res2.resultCode == 200){
            this.formList.find(item => item.fieldName ==='orgId').itemList = this.allOrgId
          }
        }
        // 3. 合并大区 传15061004
        if(isDisArea == 10041001 && isMerge == 10041001 ){
          const res3 = await getOrgType(15061014);
          this.allOrgId = res3.data.map(x=> ({ value: JSON.stringify(x), text: x.orgName }))
          console.log('经销商代码3', this.allOrgId)
          if(res3.resultCode == 200){
            this.formList.find(item => item.fieldName ==='orgId').itemList = this.allOrgId
          }
        }
        // 4. 合并大小区 传15061014， 15061015
        if(isDisArea == 10041002 && isMerge == 10041001 ){
          const res4 = await getOrgType(15061014, 15061015);
          this.allOrgId = res4.data.map(x=> ({ value: JSON.stringify(x), text: x.orgName }))
          console.log('经销商代码4', this.allOrgId)
          if(res4.resultCode == 200){
            this.formList.find(item => item.fieldName ==='orgId').itemList = this.allOrgId
          }
        }

      // if (this.type === 'edit') {
      //   // 更新接口需要的记录 ID
      //   this.recordId = this.rowData.testDriveId;
      //   this.formList.forEach(x => {
      //     x.initialValue = this.rowData[x.fieldName];
      //   });
      // }
    },
    createFormList() {
      return [
        {
          type: 'SELECT',
          label: '所属区域',
          fieldName: 'orgId',
          placeholder: '请选择',
          itemList: [],
          change:orgID=>{
            console.log('orgID', orgID)
            let newOrgId = orgID ? JSON.parse(orgID).orgId : ''
            if(newOrgId){
              getDealerArea(newOrgId,'','').then(res =>{
                console.log('根据事业部查询经销商', res)
                if (res.resultCode === 200 ) {
                  this.formList.find(item => item.fieldName ==='ownerName').itemList = res.data.map(x=> ({ value: x.dealerId, text: x.dealerName,$code:x.dealerCode }))
                }
              })
            } else {
              this.formList.find(item => item.fieldName ==='ownerName').itemList = []
              this.formList.find(item => item.fieldName ==='orgId').itemList = JSON.parse(JSON.stringify(this.allOrgId))
            }
            this.formList.find(item => item.fieldName ==='ownerName').initialValue = ''
            this.formList.find(item => item.fieldName ==='ownerCode').initialValue = ''
          }
        },
        {
          type: 'SELECT',
          label: '所属经销商',
          fieldName: 'ownerName',
          placeholder: '请选择',
          itemList: [],
          change: e=>{
            console.log(e)
            if (typeof e == 'number') {
              let itemList = this.formList.find(item => item.fieldName ==='ownerName').itemList
              let result = itemList.find(item=>item.value == e)['$code']
              this.formList.find(val => val.fieldName ==='ownerCode').initialValue = result
            } else {
              this.formList.find(item => item.fieldName ==='ownerCode').initialValue = ''
            }
          }
        },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'ownerCode',
          placeholder: '请输入',
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={this.openSearch}></el-button>;
          },
          change: (val) => {
            console.log('经销商代码',val , typeof val)
            if (typeof val == 'string' || !val) {
              this.formList2.find(item => item.fieldName ==='orgId').itemList = JSON.parse(JSON.stringify(this.allOrgId))
              this.formList2.find(item => item.fieldName ==='ownerName').itemList = []
              this.formList2.find(item => item.fieldName ==='orgId').initialValue = ''
              this.formList2.find(item => item.fieldName ==='ownerName').initialValue = ''
            }
          }
        },
      ];
    },
    async openSearch() {
      console.log(this.formList.find(item=>item.fieldName == "ownerCode").initialValue,"val")
      let ownerCodeVal =this.formList.find(item=>item.fieldName == "ownerCode").initialValue
      if (ownerCodeVal == '' || ownerCodeVal == null || ownerCodeVal == undefined) {
        console.log('请输入点内容不好么')
        return
      }
      getDealerArea('',ownerCodeVal,'').then(res =>{
        console.log('查询功能', res)
        if (res.resultCode == 200 && res.data !=[]) {
          res.data.map(x=>{
              if(x.dealerCode == ownerCodeVal ){
                this.formList.find(item => item.fieldName ==='orgId').initialValue = JSON.stringify(x)
                this.formList.find(item => item.fieldName ==='ownerName').initialValue = x.dealerId
              }
          })
          this.formList.find(item => item.fieldName ==='orgId').itemList = res.data.map(x=> ({ value: JSON.stringify(x), text: x.orgName,$code:x.orgCode }))
          let orgId = this.formList.find(item=>item.fieldName == "orgId").initialValue
          if (orgId) {
            this.formList.find(item => item.fieldName ==='ownerName').itemList = res.data.map(x=> ({ value: x.dealerId, text: x.dealerName,$code:x.dealerCode }))
          }
        }
      })
    },
    async saveDialog() {
      const { selectList } = this
      this.$refs.formPanel.SUBMIT_FORM();
      console.log('save',this.saveData)
      // 特别处理
      let saveData = JSON.parse(JSON.stringify(this.saveData))
      saveData.orgId = saveData.orgId ? JSON.parse(saveData.orgId).orgId : ''
      if (this.saveData !== null) {
        let params ={
          ...saveData,
          clueIds: selectList
        }
        const res = await updateDealers(params)
        console.log('修改经销商', res)
        if(res.resultCode == 200){
          this.closeDialog('refresh');
          this.$message.success('保存成功!');
        }
      }
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    closeDialog(param) {
      this.$emit('close', false, param);
    },
  }
};
</script>

<style lang="less" scoped>
</style>
